package com.d3works.apps.base.web;

import com.d3works.apps.base.db.PrintTemplateLine;
import com.d3works.apps.base.db.repo.PrintTemplateLineRepository;
import com.d3works.apps.base.service.PrintTemplateLineService;
import com.d3works.exception.D3worksException;
import com.d3works.exception.service.TraceBackService;
import com.d3works.inject.Beans;
import com.d3works.meta.db.MetaModel;
import com.d3works.meta.db.repo.MetaModelRepository;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import com.d3works.rpc.Context;
import java.io.IOException;

public class PrintTemplateLineController {

  public void checkTemplateLineExpression(ActionRequest request, ActionResponse response) {

    Context context = request.getContext();
    PrintTemplateLine printTemplateLine =
        Beans.get(PrintTemplateLineRepository.class)
            .find(Long.valueOf(context.get("_printTemplateLine").toString()));
    MetaModel metaModel =
        Beans.get(MetaModelRepository.class)
            .all()
            .filter("self.fullName = ?", context.get("reference"))
            .fetchOne();
    try {
      String result =
          Beans.get(PrintTemplateLineService.class)
              .checkExpression(
                  Long.valueOf(context.get("referenceId").toString()),
                  metaModel,
                  printTemplateLine);
      response.setValue("$contentResult", result);
    } catch (NumberFormatException | ClassNotFoundException | D3worksException | IOException e) {
      TraceBackService.trace(response, e);
    }
  }
}
